package com.lanou3g.ssoserver.service;

import com.lanou3g.ssoserver.bean.UserInfo;
import com.lanou3g.ssoserver.utils.SSOResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginService {

    @Autowired
    private RedisTemplate redisTemplate;

    public SSOResult login(String username, String password, HttpServletResponse resp) {
        if(username == null || password == null) {
            return new SSOResult(500, "用户名或密码不能为空!");
        }

        if(!username.equals("zhangsan")) {
            return new SSOResult(500, "用户名不存在，请先注册!");
        }

        if(username.equals("zhangsan") && !password.equals("123456")) {
            return new SSOResult(500, "用户名或密码错误!");
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
//        userInfo.setPassword(password);
        userInfo.setNickName("张三");

        // 将用户登录信息保存到redis
        String token = storeUserInfo2Redis(userInfo);

        Cookie tokenCookie = new Cookie("USER-TT", token);
        tokenCookie.setMaxAge(5 * 60);  //token过期时间1分钟

        resp.addCookie(tokenCookie);

        return new SSOResult(200, "登录成功");
    }


    /**
     * 将登录信息存储到redis
     * @param userInfo
     * @return 返回redis中对应的key token
     */
    private String storeUserInfo2Redis(UserInfo userInfo) {
        String token = UUID.randomUUID().toString();
        ValueOperations ops = redisTemplate.opsForValue();
        ops.set(token, userInfo);
        redisTemplate.expire(token, 5, TimeUnit.MINUTES);
        return token;
    }

    public UserInfo getUserByToken(String token) {
        ValueOperations ops = redisTemplate.opsForValue();
        Object userInfo = ops.get(token);
        if(userInfo != null) {
            redisTemplate.expire(token, 5, TimeUnit.MINUTES);
            return (UserInfo) userInfo;
        }
        return null;
    }
}
